package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: xuesm
 * @date: 2025/2/8 14:39
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 无需登录即可访问
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token){

        // 直接访问没有，从登录服务器过来有
        if (!StringUtils.isEmpty(token)){
            // TODO 去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String username = responseEntity.getBody();
            session.setAttribute("loginUser", username);
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            // 没登陆，跳登录服务器进行登录，同时告诉登录服务器我们是那个页面，这样登录成功后还能跳回来
            return "redirect:" + ssoServerUrl+"?redirect_url=http://client1.com:8081/employees";
        }else {
            // 登录了
            List<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            model.addAttribute("emps", list);
            return "list";
        }


    }

}
